package com.techysky.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.techysky.entity.MaintRecord;
import com.techysky.repository.MaintRecordRepository;
import com.techysky.service.MaintService;
import com.techysky.util.CoreUtils;

@Controller
@RequestMapping("/Maint")
public class MaintController implements Serializable {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private transient MaintRecordRepository maintRecordRepository;
	@Autowired
	private MaintService maintService;
	
	/**
	 * 换件统计
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/zbdzll-hjtj")
	public String zbdzllHjtj() {
		
		return "zbdzll-hjtj";
	}
	@RequestMapping("/MaintM/zbdzll-hjtj")
	@ResponseBody
	public Object operator(  int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter("search");
		// 查询数据
		return grid(pageable, search);
	}
	
	public List<Map<String, Object>> grid( PageRequest pageable, String search) {
		return CoreUtils.getInstance().convert(maintRecordRepository.findAll((Root<MaintRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb)
						->{
						List<Predicate> predicate = new ArrayList<>();
						Path<String> replacePart = root.get("replacePart");
						if (!StringUtils.isBlank(search)) {
							Predicate p = cb.and(cb.like(replacePart, "%" + search + "%"),cb.isNotNull(replacePart));
							predicate.add(p);
						}else{
							Predicate p = cb.isNotNull(replacePart);
							predicate.add(p);
						}
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();
					}
				, pageable).getContent());			
	}
	
	/**
	 * 未完成统计
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/zbdzll-wwctj")
	public String zbdzllWwctj( Model model) {
		Map map=this.maintService.getWwctj();
		model.addAttribute("wwc", map.get("wwc"));
		model.addAttribute("ywc", map.get("ywc"));
		return "zbdzll-wwctj";
	}
	
}
